//
//  InformationViewController.m
//  Logistics
//
//  Created by hy002 on 2018/1/11.
//  Copyright © 2018年 HUYU. All rights reserved.
//

#import "InformationViewController.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>

static NSString *cellPath = @"InformationCell";
@interface InformationViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate,UIScrollViewDelegate>
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)NSArray *titAry;
@property (nonatomic, strong)UIImageView *faceImgView;

@end

@implementation InformationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (_model.type == 1 && _model.company)
    {
        _titAry = @[@"头像",@"昵称",@"电话",@"真实姓名",@"入驻类型",@"公司名称",@"详细地址",@"身份证号码"];
    }
    else
    {
        _titAry = @[@"头像",@"昵称",@"电话",@"真实姓名",@"身份证号码"];
    }
    [self creatUI];
}

- (void)creatUI
{
    self.navigationItem.title = @"个人信息";
    self.view.backgroundColor = BacksColor;
    self.navigationController.navigationBar.translucent = NO;
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-SCREER_HeiX) style:UITableViewStylePlain];
    _tableview.backgroundColor = BacksColor;
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableview];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_model.isIdentify == 1)
    {
        return 2;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return _titAry.count;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = BacksColor;
    if (_model)
    {
        UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, 10*displaywidth, SCREEN_WIDTH, 70*displaywidth)];
        whiteView.backgroundColor = [UIColor whiteColor];
        [cell.contentView addSubview:whiteView];
        if (indexPath.section == 0)
        {
            if (indexPath.row == 0)
            {
                UILabel *photoLab = [ZCControl createLabelWithFrame:CGRectMake(0, 15*displaywidth, 95*displaywidth, 40*displaywidth) Font:15.0 Text:_titAry[indexPath.row] Color:BlaTitColor];
                photoLab.textAlignment = NSTextAlignmentRight;
                [whiteView addSubview:photoLab];
                UIImageView *faceView = [ZCControl createImageViewWithFrame:CGRectMake(SCREEN_WIDTH-75*displaywidth, 15*displaywidth, 40*displaywidth, 40*displaywidth) ImageName:@"morenFace"];
                if (_model.headImg.length > 0)
                {
                    [faceView sd_setImageWithURL:URL(_model.headImg) placeholderImage:IMAGE(@"morenFace")];
                }
                faceView.contentMode = UIViewContentModeScaleAspectFill;
                faceView.layer.masksToBounds = YES;
                _faceImgView = faceView;
                [whiteView addSubview:faceView];
                
            }
            else
            {
                whiteView.frame = CGRectMake(0, 10*displaywidth, SCREEN_WIDTH, 45*displaywidth);
                UILabel *titLab = [ZCControl createLabelWithFrame:CGRectMake(0, 5*displaywidth, 95*displaywidth, 35*displaywidth) Font:15.0 Text:_titAry[indexPath.row] Color:BlaTitColor];
                titLab.textAlignment = NSTextAlignmentRight;
                [whiteView addSubview:titLab];
                UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(100*displaywidth, 12.5*displaywidth, 1, 20*displaywidth)];
                line1.backgroundColor = RGB(204, 204, 204);
                [whiteView addSubview:line1];
                if (indexPath.row == 1)
                {
                    UITextField *textfield = [ZCControl createTextFieldWithFrame:CGRectMake(110*displaywidth, 2.5*displaywidth, SCREEN_WIDTH-125*displaywidth, 40*displaywidth) placeholder:@"" passWord:NO leftImageView:nil rightImageView:nil Font:13.0];
                    [textfield setValue:RGB(135, 135, 135) forKeyPath:@"_placeholderLabel.textColor"];
                    textfield.delegate = self;
                    textfield.clearButtonMode = UITextFieldViewModeWhileEditing;
                    textfield.textColor = BlaTitColor;
                    textfield.textAlignment = NSTextAlignmentLeft;
                    textfield.text = _model.username;
                    [whiteView addSubview:textfield];
                }
                else
                {
                    NSString *realName = _model.identity.realName;
                    NSString *carNum = _model.identity.idCard;
                    if (!realName)
                    {
                        realName = @"";
                        carNum = @"";
                    }
                    NSArray *nameAry = @[@"",@"",_model.phone,realName,carNum];
                    if (_model.type == 1 && _model.company)
                    {
                        nameAry = @[@"",@"",_model.phone,realName,_model.company.serveName,_model.company.companyName,_model.address,carNum];
                    }
                    UILabel *nameLab = [ZCControl createLabelWithFrame:CGRectMake(110*displaywidth, 2.5*displaywidth, SCREEN_WIDTH-125*displaywidth, 40*displaywidth) Font:14.0 Text:nameAry[indexPath.row] Color:RGB(51, 51, 51)];
                    [whiteView addSubview:nameLab];
                }
                
            }
        }
        else
        {
            whiteView.frame = CGRectMake(0, 10*displaywidth, SCREEN_WIDTH, 140*displaywidth);
            UILabel *titLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 5*displaywidth, 100*displaywidth, 35*displaywidth) Font:15.0 Text:@"居民身份证照片" Color:BlaTitColor];
            [whiteView addSubview:titLab];
            NSArray *imgArray = @[_model.identity.idCardFrontImg,_model.identity.idCardReverseImg,_model.identity.idCardImg];
            CGFloat width = (SCREEN_WIDTH-60*displaywidth)/3;
            for (int i = 0; i < 3; i++)
            {
                
                UIImageView *cardImgview = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth+(width+15*displaywidth)*i, 55*displaywidth, width, 70*displaywidth) ImageName:nil];
                [cardImgview sd_setImageWithURL:URL(imgArray[i])];
                cardImgview.backgroundColor = [UIColor grayColor];
                cardImgview.contentMode = UIViewContentModeScaleAspectFill;
                cardImgview.layer.cornerRadius = 5;
                cardImgview.layer.masksToBounds = YES;
                [whiteView addSubview:cardImgview];
            }
        }
        
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0 && indexPath.section == 0)
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"选择图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        //拍照
        WEAKSELF;
        [alertVC addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            HYLog(@"拍照");
            [weakSelf takePhoto];
            
        }]];
        
        //从相册中选取
        [alertVC addAction:[UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            HYLog(@"从相册中选取");
            [weakSelf choseImageWithTypeCameraTypePhotoLibrary:UIImagePickerControllerSourceTypePhotoLibrary];
            
        }]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            HYLog(@"取消");
            [weakSelf dismissViewControllerAnimated:NO completion:nil];
        }]];
        
        [self presentViewController:alertVC animated:YES completion:nil];
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        if (indexPath.row == 0)
        {
            return 80*displaywidth;
        }
        return 55*displaywidth;
    }
    return 150*displaywidth;
}

-(void)takePhoto
{
    //    判断是否打开相机权限
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您尚未开启相机权限，请去系统设置界面打开相机权限！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication]canOpenURL:url]) {
                [[UIApplication sharedApplication]openURL:url];
            }
        }];
        [alertVC addAction:okAction];
        [self presentViewController:alertVC animated:YES completion:nil];
        
        
    }
    else
    {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
        {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            //设置拍照后的图片可被编辑
            picker.allowsEditing = YES;
            picker.sourceType = sourceType;
            [self presentViewController:picker animated:YES completion:nil];
        }else
        {
            
        }
        
    }
}


-(void)choseImageWithTypeCameraTypePhotoLibrary:(UIImagePickerControllerSourceType)type{
    
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate =self;
    imagePicker.sourceType = type;
    imagePicker.allowsEditing = YES;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.allowsEditing =YES;
    [self presentViewController:imagePicker animated:YES completion:^{
        
    }];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage* image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    _faceImgView.image = image;
    WEAKSELF;
    [HttpTool uploadImageWithPath:@"/file/upload" params:nil thumbName:@"file" image:image success:^(id json) {
        if ([json server_Getcodecheck])
        {
            NSArray *imgAry = json[@"data"];
            if (imgAry.count > 0)
            {
                NSString *imgStr = imgAry[0];
                NSDictionary *dic = @{@"headImg":imgStr};
                [weakSelf requestSaveUser:dic];
            }
        }
    } failure:^(NSError *error) {
        
    } progress:^(CGFloat progress) {
        
    }];
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)requestSaveUser:(NSDictionary *)dic
{
    [HYBaseHandler requestWithTheFormUrl:SERVER_userSave Parmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:self.view];
        }
    } failed:^(NSError *error) {
        
    }];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField.text.length > 0)
    {
        NSDictionary *dic = @{@"username":textField.text};
        [self requestSaveUser:dic];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];

}

- (NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.view endEditing:YES];
    return indexPath;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
